<?php
declare (strict_types=1);

namespace app\api\controller;

use app\common\model\Area;
use think\facade\View;
use think\exception\ValidateException;
use app\common\model\Address as AddressModel;
use think\response\Json;

class Address extends Base
{

    public function index()
    {
        $map = ['uid' => $this->user->id, 'is_del' => 0];
        $list = AddressModel::getList($map, false, 'create_time', ['p', 'c', 'd', 't'],
            'id,nickname,tel,province,city,district,town,details,default');
        foreach ($list as $v) {
            $v->province = $v->p->title;
            $v->city = $v->c->title;
            $v->district = $v->d->title;
            $v->town = $v->t->title;
            unset($v->p);
            unset($v->c);
            unset($v->d);
            unset($v->t);
        }
        return json(['code' => 1, 'msg' => 'success', 'result' => $list]);

    }

    public function add()
    {
        return View::fetch();
    }

    public function edit($id)
    {
        $info = AddressModel::with(['p','c','d','t'])->where('id', $id)
            ->field('id,nickname,tel,province,city,district,town,details,default')->find();
        unset($info->province);
        unset($info->city);
        unset($info->district);
        unset($info->town);
        return json(['code' => 1, 'msg' => 'success', 'result' => $info]);
    }

    public function save(): Json
    {
        $param = $this->request->post('', '', $this->filter);
        try {
            $this->validate($param, 'Address');
        } catch (ValidateException $e) {
            return json(['code' => -1, 'msg' => $e->getError()]);
        }
        $result = AddressModel::add($param, $this->user);
        $result['code'] = $result['code'] > 1 ? 1 : -1;
        return json($result);

    }

    public function delete(): Json
    {
        return json(AddressModel::edit($this->request->post('id'), $this->user));
    }

    public function getArea($id, $level = 0)
    {
        $list = Area::getArea($id ?: 100000, $level);
        return json(['code' => 1, 'msg' => 'success', 'result' => $list]);
    }

    public function choice()
    {
        return json(AddressModel::choice($this->request->post('id'), $this->user));
    }

}

